package org.hxzon.emailblog.gae.pages;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Zone;
import org.hxzon.emailblog.blog.BlogFile;
import org.hxzon.emailblog.blog.BlogImage;
import org.hxzon.util.EMailUtil;
import org.hxzon.util.EMailUtil.EMail;
import org.hxzon.util.EMailUtil.EMailImage;

public class Index {
    @InjectComponent
    private Zone resultZone;
    //
    //
    @Property
    private EMail email;
    @Property
    private String tos;
    @Property
    private String emailContent;
    @Property
    private BlogFile blogFile;
    @Property
    private String result;

    @OnEvent(value = EventConstants.PREPARE, component = "form")
    void init() {
        email = new EMail();
        email.setHost("smtp.163.com");
        email.setUsername("@163.com");
        email.setFrom("@163.com");
        blogFile = new BlogFile();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "form")
    Object sendEmail() {
        //email.setHost(("email.host"));
        //email.setFrom(properties.getProperty("email.from"));
        //email.setUsername(properties.getProperty("email.username"));
        //email.setPassword(properties.getProperty("email.password"));
        email.addTosSplit(tos);
        email.setEncoding("utf-8");
        //email.setSubject(emailTitle);
        blogFile.setContentOrigl(emailContent);
        email.addHtml(blogFile.getContentEmail());
        List<BlogImage> images = blogFile.getImages();
        for (BlogImage imageInfo : images) {
            email.addAttachment(new EMailImage(imageInfo.getCid(), imageInfo.getOrigSrc()));
        }
        result = EMailUtil.sendAndWait(email, true);
        if (result == null) {
            result = "发送成功";
        }
        return resultZone.getBody();
    }

}
